package com.tronsis.distribution.activity.me.points;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageAndVideoPreviewSeeActivity;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.tronsis.distribution.R;
import com.tronsis.distribution.bean.PayeeMethodBean;
import com.tronsis.distribution.bean.UploadFileBean;
import com.tronsis.distribution.bean.WithDrawAskBean;
import com.tronsis.distribution.biz.factory.FileBizFactory;
import com.tronsis.distribution.biz.factory.UserBizFactory;
import com.tronsis.distribution.eventbus.EventMessage;
import com.tronsis.distribution.http.Url;
import com.tronsis.distribution.util.CommonUtil;
import com.tronsis.distribution.util.GlideImageLoader;
import com.tronsis.library.activity.ToolBarBaseActivity;
import com.tronsis.library.adapter.recyclerview.CommonAdapter;
import com.tronsis.library.adapter.recyclerview.base.ViewHolder;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.imageloader.ImageLoader;
import com.tronsis.library.util.StringUtil;
import com.tronsis.library.util.ToastUtil;
import com.tronsis.library.util.WindowUtil;
import com.tronsis.library.widget.ConfirmDialog;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.lzy.imagepicker.ImagePicker.REQUEST_CODE_PREVIEW;

public class PointProcessingDetailActivity extends ToolBarBaseActivity {

    @BindView(R.id.tv_phone)
    TextView mTvPhone;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.tv_payee_method)
    TextView mTvPayeeMethod;
    @BindView(R.id.ll_payee_method)
    LinearLayout mLlPayeeMethod;
    @BindView(R.id.tv_points)
    TextView mTvPoints;
    @BindView(R.id.tv_payee)
    TextView mTvPayee;
    @BindView(R.id.tv_point_price)
    TextView mTvPointPrice;
    @BindView(R.id.tv_payee_credentials)
    TextView mTvPayeeCredentials;
    @BindView(R.id.line1)
    View mViewLine;
    @BindView(R.id.ll_upload_credentials)
    LinearLayout mLlUploadCredentials;
    @BindView(R.id.ll_upload_more_credentials)
    LinearLayout mLlUploadMoreCredentials;
    @BindView(R.id.btn_submit)
    Button mBtnSubmit;
    @BindView(R.id.rv_user_upload)
    RecyclerView mRvUserUpload;
    @BindView(R.id.rv_upload)
    RecyclerView mRvUpload;

    private static final int REQ_CAMERA = 124;
    private static final int REQUEST_CAMERA = 125;
    private static final int REQUEST_ALBUM = 126;
    private PopupWindow mImagePopupWindow;


    private WithDrawAskBean mWithDrawAskBean;

    private ImageItem mImageItem = new ImageItem();
    private ArrayList<ImageItem> mImageList = new ArrayList<>();
    private CommonAdapter<ImageItem> mPayImageAdapter;
    private ImageItem mMoreImageItem = new ImageItem();
    private ArrayList<ImageItem> mMoreImageList = new ArrayList<>();
    private CommonAdapter<ImageItem> mMorePayImageAdapter;
    private boolean mShowDelete = false;
    private int selectLimit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_point_processing_detail);
        ButterKnife.bind(this);
        mWithDrawAskBean = (WithDrawAskBean) getIntent().getSerializableExtra("withDrawAskBean");
        initView(mWithDrawAskBean);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS && data != null) {
            if(StringUtil.isEquals("REPORT", mWithDrawAskBean.getState())){
                List<ImageItem> imageItems = (List<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (imageItems != null && imageItems.size() > 0) {
                    mMoreImageList.remove(mMoreImageItem);
                    mMoreImageList.addAll(imageItems);
                    if (mMoreImageList.size() < 3) {
                        mMoreImageList.add(mMoreImageItem);
                    }
                    mMorePayImageAdapter.notifyDataSetChanged();
                }
            }
            if (StringUtil.isEquals("PAY", mWithDrawAskBean.getState())) {
                List<ImageItem> imageItems = (List<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (imageItems != null && imageItems.size() > 0) {
                    mImageList.remove(mImageItem);
                    mImageList.addAll(imageItems);
                    if (mImageList.size() < 3) {
                        mImageList.add(mImageItem);
                    }
                    mPayImageAdapter.notifyDataSetChanged();
                }
            }

        }

    }

    @OnClick(R.id.btn_submit)
    void submitClick() {
        if (mImageList.contains(mImageItem) && mImageList.size() == 1) {
            ToastUtil.showMessage(this, "请添加付款凭证");
            return;
        }

        if (StringUtil.isEquals("PAY", mWithDrawAskBean.getState())) {
            httpCommitUploadFile(mImageList);
            return;
        }

        if (StringUtil.isEquals("REPORT", mWithDrawAskBean.getState())) {
            if (mMoreImageList.contains(mMoreImageItem) && mMoreImageList.size() == 1) {
                ToastUtil.showMessage(this, "请添加补交凭证");
                return;
            }
            httpCommitUploadFile(mMoreImageList);
            return;
        }

    }

    private void initView(WithDrawAskBean withDrawAskBean) {
        if (withDrawAskBean == null) {
            return;
        }
        initImageRv();
        initMoreImageRv();
        String state = withDrawAskBean.getState();
        String title = "";
        if (state != null) {
            switch (state) {
                case "PAY":
                    title = getString(R.string.wait_pay_detail);
                    mTvPayeeCredentials.setVisibility(View.GONE);
                    break;
                case "CONFIRM":
                    title = getString(R.string.wait_confirm_detail);
                    mTvPayeeCredentials.setVisibility(View.VISIBLE);
                    mLlUploadCredentials.setVisibility(View.GONE);
                    mViewLine.setVisibility(View.GONE);
                    mBtnSubmit.setVisibility(View.GONE);
                    break;
                case "REPORT":
                    title = getString(R.string.complaint_detail);
                    mTvPayeeCredentials.setVisibility(View.VISIBLE);
                    mLlUploadMoreCredentials.setVisibility(View.VISIBLE);
                    mLlUploadCredentials.setVisibility(View.GONE);
                    break;
                case "FINISH":
                    mLlUploadCredentials.setVisibility(View.GONE);
                    mTvPayeeCredentials.setVisibility(View.VISIBLE);
                    mViewLine.setVisibility(View.GONE);
                    mBtnSubmit.setVisibility(View.GONE);
                    title = getString(R.string.finish_detail);
                    break;
                default:
                    break;

            }
        }
        setTitle(true, title);

        mTvPhone.setText(getString(R.string.format_phone, withDrawAskBean.getPhone()));
        if(TextUtils.isEmpty(withDrawAskBean.getName())){
            mTvName.setText(getString(R.string.format_nick_name, "-"));
        }else{
            mTvName.setText(getString(R.string.format_nick_name, withDrawAskBean.getName()));
        }
        mTvPoints.setText(getString(R.string.format_ask_points, String.valueOf(withDrawAskBean.getPoint())));
        mTvPointPrice.setText(getString(R.string.format_amount, withDrawAskBean.getPointPrice()));

        List<PayeeMethodBean> payees = withDrawAskBean.getPayees();
        if (payees != null && payees.size() > 0) {
            PayeeMethodBean bean = payees.get(0);
            mTvPayee.setText(bean.getName() + "：" + bean.getBank() + "   " + bean.getAccount());
        }

        String paymentFid = withDrawAskBean.getPaymentFid();
        if (paymentFid != null) {
            ArrayList<ImageItem> splitImage = CommonUtil.getSplitImage(paymentFid);
            mImageList.clear();
            mImageList.addAll(splitImage);
            mPayImageAdapter.notifyDataSetChanged();
        }
    }

    private void initImageRv() {
        mImageItem.path = "";
        mImageItem.addTime = System.currentTimeMillis();
        if (StringUtil.isEquals(mWithDrawAskBean.getState(), "PAY") && mImageList.size() < 3) {
            mImageList.add(mImageItem); // 插入 + 号占位数据
        }

        mPayImageAdapter = new CommonAdapter<ImageItem>(mContext, mImageList, R.layout.item_grid_image_view) {
            @Override
            protected void convert(final ViewHolder holder, final ImageItem imageItem, final int position) {
                ImageView ivItem = (ImageView) holder.getView(R.id.iv_item);
                holder.getView(R.id.iv_delete).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showDeleteConfirmDialog(position);
                    }
                });

                if (TextUtils.isEmpty(imageItem.path) && TextUtils.isEmpty(imageItem.url)) {
                    holder.getView(R.id.iv_delete).setVisibility(View.GONE);
                    ivItem.setImageResource(R.drawable.icon_add_res);

                    ivItem.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showImagePopupWindow();
                        }
                    });

                } else {
                    if (TextUtils.isEmpty(imageItem.path)) {
                        ImageLoader.display(mContext, imageItem.url, ivItem);
                    }
                    if (TextUtils.isEmpty(imageItem.url)) {
                        ImageLoader.display(mContext, new File(imageItem.path), ivItem);
                    }

                    ivItem.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            if (StringUtil.isEquals(mWithDrawAskBean.getState(), "PAY")) {
                                if (mShowDelete) {
                                    mShowDelete = false;
                                } else {
                                    mShowDelete = true;
                                }
                                notifyDataSetChanged();
                            }
                            return false;
                        }
                    });

                    ivItem.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (TextUtils.isEmpty(mImageList.get(position).path) && TextUtils.isEmpty(mImageList.get(position).url)) {
                                return;
                            }

                            mImageList.remove(mImageItem);

                            Intent intentPreview = new Intent(mContext, ImageAndVideoPreviewSeeActivity.class);
                            intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                            intentPreview.putParcelableArrayListExtra(ImagePicker.EXTRA_IMAGE_ITEMS, mImageList);
                            startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                        }
                    });

                    if (mShowDelete) {
                        holder.getView(R.id.iv_delete).setVisibility(View.VISIBLE);
                    } else {
                        holder.getView(R.id.iv_delete).setVisibility(View.GONE);
                    }
                }
            }


        };


        mRvUserUpload.setLayoutManager(new GridLayoutManager(mContext, 3, LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mRvUserUpload.setAdapter(mPayImageAdapter);
        mRvUserUpload.setHasFixedSize(true);
        mRvUserUpload.setNestedScrollingEnabled(false);
    }

    private void initMoreImageRv() {
        mMoreImageItem.path = "";
        mMoreImageItem.addTime = System.currentTimeMillis();
        if (StringUtil.isEquals(mWithDrawAskBean.getState(), "REPORT") && mMoreImageList.size() < 3) {
            mMoreImageList.add(mMoreImageItem); // 插入 + 号占位数据
        }

        mMorePayImageAdapter = new CommonAdapter<ImageItem>(mContext, mMoreImageList, R.layout.item_grid_image_view) {
            @Override
            protected void convert(final ViewHolder holder, final ImageItem imageItem, final int position) {
                ImageView ivItem = (ImageView) holder.getView(R.id.iv_item);
                holder.getView(R.id.iv_delete).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showDeleteConfirmDialog(position);
                    }
                });

                if (TextUtils.isEmpty(imageItem.path) && TextUtils.isEmpty(imageItem.url)) {
                    holder.getView(R.id.iv_delete).setVisibility(View.GONE);
                    ivItem.setImageResource(R.drawable.icon_add_res);

                    ivItem.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showImagePopupWindow();
                        }
                    });

                } else {
                    if (TextUtils.isEmpty(imageItem.path)) {
                        ImageLoader.display(mContext, imageItem.url, ivItem);
                    }
                    if (TextUtils.isEmpty(imageItem.url)) {
                        ImageLoader.display(mContext, new File(imageItem.path), ivItem);
                    }

                    ivItem.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            if (StringUtil.isEquals(mWithDrawAskBean.getState(), "REPORT")) {
                                if (mShowDelete) {
                                    mShowDelete = false;
                                } else {
                                    mShowDelete = true;
                                }
                                notifyDataSetChanged();
                            }
                            return false;
                        }
                    });

                    ivItem.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (TextUtils.isEmpty(mMoreImageList.get(position).path) && TextUtils.isEmpty(mMoreImageList.get(position).url)) {
                                return;
                            }

                            mMoreImageList.remove(mMoreImageItem);

                            Intent intentPreview = new Intent(mContext, ImageAndVideoPreviewSeeActivity.class);
                            intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                            intentPreview.putParcelableArrayListExtra(ImagePicker.EXTRA_IMAGE_ITEMS, mMoreImageList);
                            startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                        }
                    });

                    if (mShowDelete) {
                        holder.getView(R.id.iv_delete).setVisibility(View.VISIBLE);
                    } else {
                        holder.getView(R.id.iv_delete).setVisibility(View.GONE);
                    }
                }
            }


        };


        mRvUpload.setLayoutManager(new GridLayoutManager(mContext, 3, LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mRvUpload.setAdapter(mMorePayImageAdapter);
        mRvUpload.setHasFixedSize(true);
        mRvUpload.setNestedScrollingEnabled(false);
    }

    private void showDeleteConfirmDialog(final int position) {
        ConfirmDialog mConfirmDialog = new ConfirmDialog(mContext, new ConfirmDialog.OnBottomButtonClickListener() {
            @Override
            public void onLeftButtonClick(View view) {
            }

            @Override
            public void onRightButtonClick(View view) {
                mImageList.remove(position);
                if (!mImageList.contains(mImageItem)) {
                    mImageList.add(mImageItem);
                }
                mPayImageAdapter.notifyDataSetChanged();
            }

        });
        mConfirmDialog.showDialog("确认删除？", "取消", "确认");
    }


    private void showImagePopupWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_album_camera, null);
        // 强制隐藏键盘
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        if (mImagePopupWindow == null) {

            ImagePicker imagePicker = ImagePicker.getInstance();
            imagePicker.setImageLoader(new GlideImageLoader());
            imagePicker.setCrop(false);
            imagePicker.setMultiMode(true);
            imagePicker.setShowCamera(true);

            mImagePopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            mImagePopupWindow.setFocusable(true);
            mImagePopupWindow.setOutsideTouchable(true);
            /* mImagePopupWindow.setBackgroundDrawable(new BitmapDrawable());*/
            mImagePopupWindow.setAnimationStyle(R.style.AnimationBottomDialog);
            mImagePopupWindow.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    if (motionEvent.getAction() == MotionEvent.ACTION_OUTSIDE) {
                        mImagePopupWindow.dismiss();
                        return true;
                    }
                    return false;
                }
            });
            mImagePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowUtil.setPopWindowBackgroundAlpha(PointProcessingDetailActivity.this, 1f);
                }
            });
            view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mImagePopupWindow.dismiss();
                }
            });
            view.findViewById(R.id.btn_camera).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mImagePopupWindow.dismiss();
                    checkPermission(new CheckPermListener() {
                        @Override
                        public void superPermission() {
                            Intent intent = new Intent(mContext, ImageGridActivity.class);
                            intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true);
                            intent.putExtra(ImageGridActivity.EXTRAS_IMAGES, (Serializable) mImageList);
                            startActivityForResult(intent, REQUEST_CAMERA);
                            mImagePopupWindow.dismiss();
                        }
                    }, R.string.ask_again, Manifest.permission.CAMERA);
                }
            });
            if(StringUtil.isEquals("PAY", mWithDrawAskBean.getState())){
                selectLimit=4 - mImageList.size();
            }else{
                selectLimit=4 - mMoreImageList.size();
            }
            view.findViewById(R.id.btn_album).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mImagePopupWindow.dismiss();
                    checkPermission(new CheckPermListener() {
                        @Override
                        public void superPermission() {
                            ImagePicker.getInstance().setSelectLimit(selectLimit);
                            Intent intent = new Intent(mContext, ImageGridActivity.class);
                            intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, false);
                            startActivityForResult(intent, REQUEST_ALBUM);
                            mImagePopupWindow.dismiss();
                        }
                    }, R.string.ask_again, Manifest.permission.READ_EXTERNAL_STORAGE);
                }
            });
        }
        WindowUtil.setPopWindowBackgroundAlpha(this, 0.7f);
        mImagePopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }


    private void httpCommitUploadFile(final List<ImageItem> customImageList) {
        final ArrayList<File> fileList = new ArrayList<>();

        for (ImageItem imageItem : customImageList) {
            if (!TextUtils.isEmpty(imageItem.path)) {
                fileList.add(new File(imageItem.path));
            }
        }

        try {
            FileBizFactory.createBiz().uploads(this, fileList, Url.FILE_TYPE_IMAGE, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    List<UploadFileBean> fileBeanList = (List<UploadFileBean>) data;
                    List<String> fileIds = new ArrayList<>();
                    for (ImageItem imageItem : customImageList) {
                        if (!TextUtils.isEmpty(imageItem.url)) {
                            String id = imageItem.url.replace(Url.FILE_DOWNLOAD, "");
                            fileIds.add(id);
                        }
                    }
                    for (UploadFileBean uploadFileBean : fileBeanList) {
                        fileIds.add(uploadFileBean.getId());
                    }

                    String ids = StringUtil.arrayList(fileIds);

                    if (StringUtil.isEquals("PAY", mWithDrawAskBean.getState())) {
                        httpUploadCredentials(ids);
                    } else if (StringUtil.isEquals("REPORT", mWithDrawAskBean.getState())) {
                        httpUploadMoreCredentials(ids);
                    }

                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            dismissLoadingDialog();
        }

    }

    private void httpUploadCredentials(String paymentFid) {
        try {
            UserBizFactory.createBiz().payPointAskWithDraw(this, mWithDrawAskBean.getId(), paymentFid, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    EventBus.getDefault().post("刷新列表");
                    setResult(RESULT_OK);
                    finish();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });

        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }

    private void httpUploadMoreCredentials(String paymentFid) {
        try {
            UserBizFactory.createBiz().payMorePointAskWithDraw(this, mWithDrawAskBean.getId(), paymentFid, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    EventBus.getDefault().post(new EventMessage(101,"刷新列表"));
                    setResult(RESULT_OK);
                    finish();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });

        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }
}
